#include <string.h>
#include <stdlib.h> 
#include <unistd.h>  
#include <stdio.h>
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <arpa/inet.h>

#define MAXLINE 256

char *g_address;
char *g_port;

/* sends/receives data to/from the server */
void str_cli(FILE *fp, int sockfd)
{
	char sendline[MAXLINE], recvline[MAXLINE];
	
	printf("Connected to server(%s : %s)\n", g_address, g_port);
	printf("Message from server : ");
	if (readline(sockfd, recvline, MAXLINE) == 0) {
		printf("str_cli: server terminated prematurely\n");
		exit(1);
	}
	fputs(recvline, stdout);
	printf("\nMessage to server (q to quit) :\n");
	
	while (fgets(sendline, MAXLINE, fp) != NULL) {

		if (strcmp(sendline, "q\n") == 0)
			break;
		writen(sockfd, sendline, strlen(sendline));

		if (readline(sockfd, recvline, MAXLINE) == 0) {
			printf("str_cli: server terminated prematurely\n");
			exit(1);
		}
		printf("Message from server : ");
		fputs(recvline, stdout);
		
		if (strcmp(recvline, "Congratulations!\n") == 0)
			break;
		printf("\nMessage to server (q to quit) :\n");
	}
}


int main(int argc, char **argv)
{
	int	sockfd;
	struct sockaddr_in	servaddr;
	int port;

	if (argc != 3) {
		printf("usage: echoclient <IPaddress> <PORT>\n");
		return 1;
	}

	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	port = atoi(argv[2]);
	
	g_address = argv[1];
	g_port = argv[2];
	
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	
	servaddr.sin_port = htons(port);
	inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

	str_cli(stdin, sockfd);		/* do it all */

	exit(0);
}
